package com.xunmall.wechat.interceptor;

import com.xunmall.base.util.JsonUtils;
import com.xunmall.base.util.SpringUtils;
import com.xunmall.wechat.model.JsAPISign;
import com.xunmall.wechat.model.constant.WeChatLinkConstant;
import com.xunmall.wechat.service.impl.WeChatService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

public class JSSDKConfigServlet extends HttpServlet {

    private static final Logger logger = LoggerFactory.getLogger(JSSDKConfigServlet.class);

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter();
        try {
            //1、获取AccessToken
            String accessToken = SpringUtils.getBean(WeChatService.class).getGlobalAccessToken(WeChatLinkConstant.APP_ID,WeChatLinkConstant.APP_SECRET).getAccessToken();
            //2、获取Ticket
            String jsapi_ticket = SpringUtils.getBean(WeChatService.class).getGlobalJsSdkTicket(accessToken).getTicket();
            //3、时间戳和随机字符串
            String noncestr = UUID.randomUUID().toString().replace("-", "").substring(0, 16);//随机字符串
            String timestamp = String.valueOf(System.currentTimeMillis() / 1000);//时间戳

            logger.info("\naccessToken:" + accessToken
                    + "\njsapi_ticket:" + jsapi_ticket
                    + "\n时间戳：" + timestamp
                    + "\n随机字符串：" + noncestr);

            //4、获取url
            String url = request.getParameter("regurl");
            logger.info("获取到待注册页面的url为：" + url);

            //5、将参数排序并拼接字符串
            String str = "jsapi_ticket=" + jsapi_ticket + "&noncestr=" + noncestr + "&timestamp=" + timestamp + "&url=" + url;

            //6、将字符串进行sha1加密
            String signature = SHA1(str);
            logger.info("签名：" + signature);

            // 发送到前台
            JsAPISign jsAPISign = new JsAPISign(false, WeChatLinkConstant.APP_ID, timestamp, noncestr, signature);
            String result = JsonUtils.toJson(jsAPISign);
            logger.info("发送到前台的参数：" + result);
            out.print(result);
        } catch (Exception e) {
            e.printStackTrace();
            out.print("error");
        }
        out.flush();
        out.close();
    }

    /**
     * 签名算法
     *
     * @param decript
     * @return
     */
    public static String SHA1(String decript) {
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-1");
            digest.update(decript.getBytes());
            byte[] messageDigest = digest.digest();
            // Create Hex String
            StringBuffer hexString = new StringBuffer();
            // 字节数组转换为 十六进制 数
            for (int i = 0; i < messageDigest.length; i++) {
                String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
                if (shaHex.length() < 2) {
                    hexString.append(0);
                }
                hexString.append(shaHex);
            }
            return hexString.toString();

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }
}

